<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-type" content="text/html; charset=utf-8">
		<title>MVC DOH Test</title>

		<style>
			@import "../../../../dojo/resources/dojo.css";
			@import "../../../../dijit/tests/css/dijitTests.css";
			@import "../css/app-format.css";
		</style>

		<!-- required: the default dijit theme: -->
		<link id="themeStyles" rel="stylesheet" href="../../../../dijit/themes/claro/claro.css">

		<!-- required: dojo.js -->
		<script src="../../../../dojo/dojo.js" type="text/javascript" data-dojo-config="parseOnLoad: 0, isDebug: 1, mvc: {debugBindings: 1}"></script>
		<script type="text/javascript" src="./helpers.js"></script>

		<script type="text/javascript" >
		var lookup, loanModel, validHousingPercentConverter = {
				format: function(value){
					return value <= 33;
				}
			}, nonZeroRelevanceConverter = {
				format: function(value){
					return value <= 0;
				}
			};

		require([
				"doh/runner",
				"dojo/_base/declare",
				"dojo/dom",
				"dojo/_base/array",
				"dojo/_base/lang",
				"dojo/request/xhr",
				"dojo/parser",
				"dojo/when",
				"dijit/registry",				
				"dojox/charting/Chart",
				"dojox/charting/themes/PlotKit/blue",
				"dojox/mvc/at",
				"dojox/mvc/computed",
				"dojo/Stateful",
				"dojox/mvc/StatefulSeries",
				"dijit/form/TextBox",
				"dijit/form/Button",
				"dijit/form/ValidationTextBox",
				"dijit/form/NumberTextBox",
				"dojox/charting/plot2d/Pie",
				"dojox/mvc/_TextBoxExtensions",
				"dojox/mvc/Group",
				"dojox/mvc/ModelRefController",
				"dojox/mvc/Output",
				"dojo/domReady!"
			], function(doh, declare, ddom, array, lang, dxhr, parser, when, registry, Chart, blue, at, computed, Stateful, StatefulSeries){

				lookup = function(model){
					if(isNaN(model.get("Zip"))){ return; }
					dxhr.get("../zips/" + model.get("Zip") + ".json", {
						content: {postalcode: model.get("Zip"), country: model.get("County")},
						preventCache: true,
						handleAs: "json"
					}).then(function(data){
						model.set("City", data.postalcodes[0].placeName);
						model.set("County", data.postalcodes[0].adminName2);
						model.set("State", data.postalcodes[0].adminCode1);
						model.set("isZipValid", true);
					}, function(e){
						model.set("City", "");
						model.set("County", "");
						model.set("State", "");
						model.set("isZipValid", false);
					});	
				};

				loanModel = new Stateful({
					Name: "John Doe",
					Street: "",
					City: "",
					County: "",
					State: "",
					Zip: "",
					Country: "US",
					BaseIncome: 50000,
					BonusIncome: 10000,
					Mortgage: 1000,
					Taxes: 500,
					OtherHousing: 1200
				});

				computed(loanModel, "TotalIncome", function(BaseIncome, BonusIncome){
					return BaseIncome + BonusIncome;
				}, at(loanModel, "BaseIncome"), at(loanModel, "BonusIncome"));

				computed(loanModel, "TotalHousing", function(Mortgage, Taxes, OtherHousing){
					return Mortgage + Taxes + OtherHousing;
				}, at(loanModel, "Mortgage"), at(loanModel, "Taxes"), at(loanModel, "OtherHousing"));

				computed(loanModel, "HousingPercent", function(TotalHousing, TotalIncome){
					return Math.round(TotalHousing / TotalIncome * 100);
				}, at(loanModel, "TotalHousing"), at(loanModel, "TotalIncome"));

				computed(loanModel, "HousingPercentError", function(HousingPercent){
					return HousingPercent > 33 ? "Housing should be less than 1/3 total expenses!" : "";
				}, at(loanModel, "HousingPercent"));

				computed(loanModel, "HousingPercentDisabled", function(HousingPercent){
					return HousingPercent <= 0 ? "disabled" : null;
				}, at(loanModel, "HousingPercent"));

				when(parser.parse(), function(){
					new Chart("expenseChart")
					 .setTheme(blue)
					 .addPlot("default", {type: "Pie"})
					 .addSeries("default", new StatefulSeries([at(loanModel, "Mortgage"), at(loanModel, "Taxes"), at(loanModel, "OtherHousing")])).render();

					 // should be able to verify all of the inputs
					doh.register("Check values and bindings", [
						{
							name: "Initial",
							runTest: function(){
								doh.is("5", registry.byId("percentHousing").get('value'),"percentHousing should be 5");
								doh.is(true, registry.byId("percentHousing").isValid(), "isValid()","percentHousing should be valid");
								doh.is("1000", registry.byId("housing").get('value'),"housing should be 1000");
								doh.is("2700", registry.byId("totalHousing").get('value'),"totalHousing should be 2700");
							}
						}, {
							name: "setZipTest",
							runTest: function(){
								registry.byId("zipInput").focus();
								registry.byId("zipInput").set('value', "11111");
								var dfd = new doh.Deferred();
								setTimeout(function(){
									try{
										registry.byId("cityInput").focus();
									}catch(e){
										return dfd.errback(e);
									}
									setTimeout(function(){
										try{
											doh.t(/^\s*$/.test(registry.byId("cityInput").get('value')), "bad zip should not display the city");
											doh.is(false, registry.byId("zipInput").isValid(), "zipInput should be invalid");
											// now try a good one
											registry.byId("zipInput").focus();
											registry.byId("zipInput").set('value', "10706");
											registry.byId("cityInput").focus();
										}catch(e){
											return dfd.errback(e);
										}
										setTimeout(function(){
											try{
												doh.is("Hastings On Hudson", registry.byId("cityInput").get('value'),"good zip 10706 should display the city");
												return dfd.callback(true);
											}catch(e){
												return dfd.errback(e);
											}
										}, 2000);							
									}, 2000);
								}, 1000);
								return dfd;							
							},
							timeout: 10000
						}, {
							name: "setMortgageTest",
							runTest: function(){
								registry.byId("housing").focus();
								registry.byId("housing").set('value', "10000");
								registry.byId("totalHousing").focus();
								var dfd = new doh.Deferred();
								setTimeout(function(){
									try{
										doh.is("20", registry.byId("percentHousing").get('value'),"percentHousing should be 5");
										doh.is(true, registry.byId("percentHousing").isValid(), "isValid()","percentHousing should be valid");
										doh.is("10000", registry.byId("housing").get('value'),"housing should be 10000");
										doh.is("11700", registry.byId("totalHousing").get('value'),"totalHousing should be 11700");
										dfd.callback(true);
									}catch(e){
										dfd.errback(e);
									}
								}, 500);
								return dfd;
							}
						}, {
							name: "setMortgageTest2",
							runTest: function(){
								registry.byId("housing").focus();
								registry.byId("housing").set('value', "20000");
								registry.byId("totalHousing").focus();
								var dfd = new doh.Deferred();
								setTimeout(function(){
									try{
										doh.is("36", registry.byId("percentHousing").get('value'),"percentHousing should be 5");
										doh.is(false, registry.byId("percentHousing").isValid(), "isValid()","percentHousing should not be valid");
										doh.is("20000", registry.byId("housing").get('value'),"housing should be 10000");
										doh.is("21700", registry.byId("totalHousing").get('value'),"totalHousing should be 11700");
										return dfd.callback(true);
									}catch(e){
										return dfd.errback(e);
									}
								}, 500);
								return dfd;
							}
						}, {
							name: "setHousingZero",
							runTest: function(){
								registry.byId("housing").focus();
								registry.byId("housing").set('value', "0");
								registry.byId("taxes").focus();
								registry.byId("taxes").set('value', "0");
								registry.byId("otherHousing").focus();
								registry.byId("otherHousing").set('value', "0");
								registry.byId("totalHousing").focus();
								var dfd = new doh.Deferred();
								setTimeout(function(){
									try{
										doh.is("0", registry.byId("housing").get('value'),"housing should be 0");
										doh.is("0", registry.byId("taxes").get('value'),"taxes should be 0");
										doh.is("0", registry.byId("otherHousing").get('value'),"otherHousing should be 0");
										doh.is("0", registry.byId("totalHousing").get('value'),"totalHousing should be 0");
										doh.is(true, registry.byId("totalHousing").get("disabled"), "disabled()","totalHousing should be disabled");
										doh.is(true, registry.byId("percentHousing").get("disabled"), "disabled()","percentHousing should disabled");
										doh.is("0", registry.byId("percentHousing").get('value'),"percentHousing should be 5");
										doh.is(true, registry.byId("percentHousing").isValid(), "isValid()","percentHousing should be valid");
										return dfd.callback(true);
									}catch(e){
										return dfd.errback(e);
									}
								}, 500);
								return dfd;
							}
						}, {
							name: "setHousingBack",
							runTest: function(){
								registry.byId("housing").focus();
								registry.byId("housing").set('value', "1000");
								registry.byId("taxes").focus();
								registry.byId("taxes").set('value', "500");
								registry.byId("otherHousing").focus();
								registry.byId("otherHousing").set('value', "1200");
								registry.byId("totalHousing").focus();
								var dfd = new doh.Deferred();
								setTimeout(function(){
									try{
										doh.is("5", registry.byId("percentHousing").get('value'),"percentHousing should be 5");
										doh.is(true, registry.byId("percentHousing").isValid(), "isValid()","percentHousing should be valid");
										doh.is("1000", registry.byId("housing").get('value'),"housing should be 1000");
										doh.is("2700", registry.byId("totalHousing").get('value'),"totalHousing should be 2700");
										doh.is(false, registry.byId("totalHousing").get("disabled"), "disabled()","totalHousing should be disabled");
										doh.is(false, registry.byId("percentHousing").get("disabled"), "disabled()","percentHousing should disabled");
										doh.is(true, registry.byId("percentHousing").isValid(), "isValid()","percentHousing should be valid");
										return dfd.callback(true);
									}catch(e){
										return dfd.errback(e);
									}
								}, 500);
								return dfd;
							}
						}
					]);

					doh.run();
				});
			});
		</script>
	</head>
	<body class="claro" style="background-image: url(../images/validating_form_pattern.png)">
		<script type="dojo/require">at: "dojox/mvc/at"</script>
		<h1 class="testTitle">doh_mvc_loan-stateful.html automated tests (non-robot)</h1>
		<div id="wrapper">
			<div id="addressLookupController" class="dijitDisplayNone" data-dojo-type="dojox.mvc.ModelRefController"
			 data-dojo-props="model: loanModel, ownProps: {_setZipAttr: 1, _setCountyAttr: 1}">
				<script type="dojo/method" event="_setZipAttr" args="value">
					var changed = this.model.Zip != value;
					this.model._changeAttrValue("Zip", value);
					if(changed){
						lookup(this.model);
					}
					return this;
				</script>
				<script type="dojo/method" event="_setCountyAttr" args="value">
					var changed = this.model.County != value;
					this.model._changeAttrValue("County", value);
					if(changed){
						lookup(this.model);
					}
					return this;
				</script>
			</div>
			<div id="header">
				<div id="navigation">
				</div>
				<div id="headerInsert">
					<h1>Big Red Loan</h1>
					<h2>The one to choose when you're in the red...</h2>
				</div>
			</div>
			<div id="main">
				<div id="leftNav"></div>
				<div id="mainContent" data-dojo-type="dojox.mvc.Group" data-dojo-props="target: at('widget:addressLookupController')">
					<h3>Borrower information</h3>
					<hr size="6" class="rule"/>
					<div class="spacer"></div>
					<div class="row">
						<div class="cell"><label for="borrowerInput">Name:</label></div>
						<div class="cell">
							<input id="borrowerInput" data-dojo-type="dijit.form.TextBox" data-dojo-props="value: at('rel:', 'Name')"/>
						</div>
					</div>
					<div class="row">
						<div class="cell"><label for="zipInput">Zipcode (try 10706):</label></div>
						<div class="cell">
							<input id="zipInput" data-dojo-type="dijit.form.NumberTextBox"
							 data-dojo-props="value: at('rel:', 'Zip'), valid: at('rel:', 'isZipValid')"
							 constraints="{pattern:'#'}" regExp="\d{5}" required="true" invalidMessage="Invalid Zip Code."/>
						</div>
					</div>
					<div class="row">
						<div class="cell"><label for="cityInput">City:</label></div>
						<div class="cell">
							<input id="cityInput" data-dojo-type="dijit.form.TextBox" data-dojo-props="value: at('rel:', 'City')"/>
						</div>
					</div>
					<div class="row">
						<div class="cell"><label for="countyInput">County:</label></div>
						<div class="cell">
							<input id="countyInput" data-dojo-type="dijit.form.TextBox" data-dojo-props="value: at('rel:', 'County')"/>
						</div>
					</div>
					<div class="row">
						<div class="cell"><label for="stateInput">State:</label></div>
						<div class="cell">
							<input id="stateInput" data-dojo-type="dijit.form.TextBox" data-dojo-props="value: at('rel:', 'State')"/>
						</div>
					</div>
					<div class="spacer"></div>
					<h3>Expenses</h3>
					<hr size="6" class="rule"/>
					<div class="spacer"></div>
					<table style="width:900px;">
						<tr style="width:900px;">
							<td style="width:400px;">
								<div class="row">
									<div class="cell"><label for="housing">Mortgage:</label></div>
									<div class="cell">
										<input id="housing" data-dojo-type="dijit.form.NumberTextBox" data-dojo-props="value: at('rel:', 'Mortgage')"/>
									</div>
								</div>
								<div class="row">
									<div class="cell">
										<label>Real Estate Taxes:</label>
									</div>
									<div class="cell">
										<input id="taxes" data-dojo-type="dijit.form.NumberTextBox" data-dojo-props="value: at('rel:', 'Taxes')"/>
									</div>
								</div>
								<div class="row">
									<div class="cell"><label>Other Housing:</label></div>
									<div class="cell">
										<input id="otherHousing" type="text" data-dojo-type="dijit.form.NumberTextBox" data-dojo-props="value: at('rel:', 'OtherHousing')"/>
									</div>
								</div>
								<div class="row">
									<div class="cell"><label for="transportation">Total Housing:</label></div>
									<div class="cell">
										<input id="totalHousing" data-dojo-type="dijit.form.NumberTextBox"
										 data-dojo-props="value: at('rel:', 'TotalHousing'),
										                  disabled: at('rel:', 'TotalHousing').direction(at.from).transform(nonZeroRelevanceConverter)"/>
									</div>
								</div>
							</td>
							<td style="width:200px;">
								<div id="expenseChart" width="150" height="150" style="display:block; width: 150px; height: 150px;"></div>
							</td>
						</tr>
					</table>
					<h3>Income</h3>
					<hr size="6" class="rule"/>
					<div class="spacer"></div>
					<div class="row">
						<div class="cell"><label for="baseIncome">Base Income:</label></div>
						<div class="cell">
							<input id="baseIncome" type="text" data-dojo-type="dijit.form.NumberTextBox" data-dojo-props="value: at('rel:', 'BaseIncome')"/>
						</div>
					</div>
					<div class="row">
						<div class="cell"><label>Bonus Income:</label></div>
						<div class="cell">
							<input id="bonusIncome" type="text" data-dojo-type="dijit.form.NumberTextBox" data-dojo-props="value: at('rel:', 'BonusIncome')"/>
						</div>
					</div>
					<div class="row">
						<div class="cell"><label for="total">Total Income:</label></div>
						<div class="cell">
							<input id="total" data-dojo-type="dijit.form.NumberTextBox" data-dojo-props="value: at('rel:', 'TotalIncome')"/>
						</div>
					</div>
					<h3>Analysis</h3>
					<hr size="6" class="rule"/>
					<div class="spacer"></div>
					<div class="row">
						<div class="cell"><label for="percentHousing">Percent housing (under 33%):</label></div>
						<div class="cell">
							<input id="percentHousing" data-dojo-type="dijit.form.NumberTextBox"
							 data-dojo-props="value: at('rel:', 'HousingPercent'),
							                  valid: at('rel:', 'HousingPercent').direction(at.from).transform(validHousingPercentConverter),
							                  disabled: at('rel:', 'HousingPercent').direction(at.from).transform(nonZeroRelevanceConverter)"
							 invalidMessage="Housing should be less than 1/3 total expenses!"/>
						</div>
					</div>
				</div>
			</div>
		</div>
	</body>
</html>
